<template>
    <div>
        <!-- 搜索栏 -->
        <div class="card" style="margin-bottom: 5px">
            <el-input style="width: 240px; margin-right: 10px" v-model="data.roomType" placeholder="请输入房间类型查询（如：海景房）"
                prefix-icon="Search"></el-input>
            <el-button type="primary" @click="load">查 询</el-button>
            <el-button type="warning" @click="reset">重 置</el-button>
        </div>

        <!-- 操作按钮 -->
        <div class="card" style="margin-bottom: 5px">
            <el-button type="primary" @click="handleAdd">新 增 房 间</el-button>
            <el-button type="danger" @click="delBatch">批 量 删 除</el-button>
        </div>

        <!-- 数据表格 -->
        <div class="card" style="margin-bottom: 5px">
            <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="房间ID" prop="id" />
                <el-table-column label="酒店名称" prop="hotelName" />
                <el-table-column label="房间类型" prop="roomType" />
                <el-table-column label="价格（元）" prop="price" />
                <el-table-column label="可用数量" prop="quantity" />
                <el-table-column label="设施信息" prop="amenities" show-overflow-tooltip />
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle></el-button>
                        <el-button @click="del(scope.row.id)" type="danger" :icon="Delete" circle></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div style="margin-top: 15px">
                <el-pagination @size-change="load" @current-change="load" v-model:current-page="data.pageNum"
                    v-model:page-size="data.pageSize" :page-sizes="[5, 10, 15, 20]" background
                    layout="total, sizes, prev, pager, next, jumper" :total="data.total" />
            </div>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog title="房间信息" v-model="data.formVisible" width="600px" destroy-on-close>
            <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="100px"
                style="padding: 20px 40px 0 0">
                <!-- 酒店ID -->
                <el-form-item label="酒店ID" prop="hotelId">
                    <el-input v-model="data.form.hotelId" autocomplete="off" placeholder="请输入关联的酒店ID" />
                </el-form-item>

                <!-- 房间类型 -->
                <el-form-item label="房间类型" prop="roomType">
                    <el-input v-model="data.form.roomType" autocomplete="off" placeholder="请输入房间类型（如：海景房）" />
                </el-form-item>

                <!-- 价格 -->
                <el-form-item label="价格（元）" prop="price">
                    <el-input-number v-model="data.form.price" :min="0" placeholder="请输入房间价格" />
                </el-form-item>

                <!-- 可用数量 -->
                <el-form-item label="可用数量" prop="quantity">
                    <el-input-number v-model="data.form.quantity" :min="0" placeholder="请输入可用房间数量" />
                </el-form-item>

                <!-- 设施信息 -->
                <el-form-item label="设施信息" prop="amenities">
                    <el-input type="textarea" :rows="3" v-model="data.form.amenities"
                        placeholder="请输入设施信息（如：WiFi、双床）" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.formVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save">保 存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { Edit, Delete, Search } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

// 初始化响应式数据
const data = reactive({
    roomType: null,          // 搜索条件：房间类型
    tableData: [],           // 表格数据
    pageNum: 1,              // 当前页码
    pageSize: 10,            // 每页数量
    total: 0,                // 总记录数
    formVisible: false,      // 对话框可见性
    form: {},                // 表单数据（新增/编辑）
    ids: [],                 // 选中的房间ID列表
    rules: {                 // 表单校验规则
        hotelId: [{ required: true, message: '请输入酒店ID', trigger: 'blur' }],
        roomType: [{ required: true, message: '请输入房间类型', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        quantity: [{ required: true, message: '请输入可用数量', trigger: 'blur' }]
    }
});

const formRef = ref();  // 表单引用

// 加载分页数据（调用后端 /room/selectPage 接口）
const load = () => {
    request.get('/room/selectPage', {
        params: {
            pageNum: data.pageNum,
            pageSize: data.pageSize,
            roomType: data.roomType  // 传递搜索条件到后端
        }
    }).then(res => {
        data.tableData = res.data.list;  // 表格数据
        data.total = res.data.total;     // 总记录数
    });
};
load();  // 初始化加载

// 重置搜索条件
const reset = () => {
    data.roomType = null;
    load();
};

// 打开新增对话框
const handleAdd = () => {
    data.formVisible = true;
    data.form = {};  // 清空表单
};

// 保存（新增/编辑）
const save = () => {
    formRef.value.validate(valid => {
        if (!valid) return;  // 校验失败
        data.form.id ? update() : add();  // 根据是否有id判断是新增还是编辑
    });
};

// 新增房间（调用后端 /room/add 接口）
const add = () => {
    request.post('/room/add', data.form).then(res => {
        if (res.code === '200') {
            data.formVisible = false;
            ElMessage.success('新增房间成功');
            load();  // 刷新数据
        } else {
            ElMessage.error(res.msg);
        }
    });
};

// 打开编辑对话框（深拷贝避免影响原数据）
const handleUpdate = (row) => {
    data.form = JSON.parse(JSON.stringify(row));  // 深拷贝
    data.formVisible = true;
};

// 编辑房间（调用后端 /room/update 接口）
const update = () => {
    request.put('/room/update', data.form).then(res => {
        if (res.code === '200') {
            data.formVisible = false;
            ElMessage.success('更新房间成功');
            load();  // 刷新数据
        } else {
            ElMessage.error(res.msg);
        }
    });
};

// 单条删除（调用后端 /room/deleteById/{id} 接口）
const del = (id) => {
    ElMessageBox.confirm('删除后无法恢复，确认删除？', '提示', { type: 'warning' })
        .then(() => {
            request.delete(`/room/deleteById/${id}`).then(res => {
                if (res.code === '200') {
                    ElMessage.success('删除成功');
                    load();  // 刷新数据
                } else {
                    ElMessage.error(res.msg);
                }
            });
        });
};

// 批量删除（调用后端 /room/deleteBatch 接口）
const delBatch = () => {
    if (data.ids.length === 0) {
        ElMessage.warning('请选择要删除的房间');
        return;
    }
    ElMessageBox.confirm('删除后无法恢复，确认删除？', '提示', { type: 'warning' })
        .then(() => {
            request.delete('/room/deleteBatch', { data: data.ids }).then(res => {
                if (res.code === '200') {
                    ElMessage.success('批量删除成功');
                    load();  // 刷新数据
                } else {
                    ElMessage.error(res.msg);
                }
            });
        });
};

// 处理表格选中项（获取选中的ID列表）
const handleSelectionChange = (rows) => {
    data.ids = rows.map(row => row.id);
};
</script>

<style scoped>
/* 可选样式调整 */
.el-table .el-table__cell {
    padding: 8px 0;
}
</style>